package com.amgl.recyclerviewwithheaderfooter;

import android.support.annotation.IntDef;

import com.amgl.recyclerviewwithheaderfooter.footer.ILoadingView;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * RecyclerView 加载更多
 * Created by amglh on 2016/8/10.
 */
public class DefaultScrollToLoadMoreListener extends ScrollToLastItemListener {
    public static final int STATE_IDLE = 0;
    public static final int STATE_LOADING = 1;
    public static final int STATE_END = 2;
    public static final int STATE_ERROR = 3;

    private LoadMoreListener mLoadMoreListener;

    public DefaultScrollToLoadMoreListener(LoadMoreListener loadMoreListener) {
        this.mLoadMoreListener = loadMoreListener;
    }

    @IntDef({STATE_IDLE, STATE_LOADING, STATE_END, STATE_ERROR})
    @Retention(RetentionPolicy.SOURCE)
    public @interface LoadingState {

    }

    int mLoadingState = STATE_IDLE;

    ILoadingView mLoadingView;

    public void setLoadingView(ILoadingView loadingView) {
        this.mLoadingView = loadingView;
    }

    public void setLoadingState(@LoadingState int state) {
        this.mLoadingState = state;
        if (mLoadingView != null)
            switch (state) {
                case STATE_IDLE:
                    mLoadingView.showNormalView();
                    break;
                case STATE_LOADING:
                    mLoadingView.showLoadingView();
                    break;
                case STATE_END:
                    mLoadingView.showEndView();
                    break;
                case STATE_ERROR:
                    mLoadingView.showErrorView("");
                    break;
            }
    }

    @Override
    protected void isScrollToLast(int lastVisiblePosition) {
        if (mLoadingState == STATE_LOADING)
            return;

        if (isLastPage()) {
            setLoadingState(STATE_END);
            return;
        }

        if (canLoadMore(lastVisiblePosition)) {
            setLoadingState(STATE_LOADING);
            loadMore();
        } else {
            setLoadingState(STATE_IDLE);
        }

    }

    /**
     * 加载更多
     */
    private void loadMore() {
        if (mLoadMoreListener != null) {
            mLoadMoreListener.loadMore();
        }
    }

    /**
     * 是否最后一页
     *
     * @return
     */
    private boolean isLastPage() {
        if (mLoadMoreListener != null) {
            return mLoadMoreListener.isLastPage();
        }
        return false;
    }

    /**
     * 是否加载更多
     * <p/>
     * 最后一个Item的位置大于PageSize，表明至少加载了一页数据。
     * <p/>
     * PageSize设置多于一屏显示的数量，否则在当前屏幕滚动时loadMore()会被调用,与下拉刷新冲突
     *
     * @param lastVisiblePosition
     * @return
     */
    private boolean canLoadMore(int lastVisiblePosition) {
        if (mLoadMoreListener != null) {
            return lastVisiblePosition >= mLoadMoreListener.getPageSize() - 1;
        }
        return false;
    }
}
